<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>twitterME</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>
	<body>
	
	<?php
	
	
		function dump($text) {
			$fp = fopen('c:\\log\dump.txt', 'w');
			if(!$fp) {
				print 'Error creating file';
				return 0;
			}
			else {
				fwrite($fp, $text);
				fclose($fp);
			}		
		}
	

		$userName = "";
	  	$password = "";
	  	$status   = "";
	  	$twitterResponse = "";
	
 	
		if(checkItem('username') && checkItem('pwd')) {
			$userName = $_POST['username'];
			$password = $_POST['pwd'];
			if(checkItem('status')) {
				$status = $_POST['status'];
			}
		}
	  	
	  	if(strlen($userName) == 0 || strlen($password) == 0) {
			Error(1);
		}
		else {
			?>
			<p>
			<b>What are you doing?</b><br>
			<form action="http://demo.ilabs.no/test/widgets/twitter/twitteraudio.php" id="signinform" method="post" enctype="multipart/form-data">
				<input name="username" type="hidden" value="<?php echo $userName?>" />
            	<input name="pwd" type='hidden' value="<?php echo $password?>" />
				<textarea name="status"></textarea>
				<!--  <INPUT TYPE="file" name="image_file" id="image_file"/> --> 
				<object name="image_file" classid="clsid:5eb72431-8e47-45a2-a6ba-609af9f051b9" width="60" height="80" type="recorder"></object>
				<input type="submit"  name="update" value="Update"/>
			</form>
			<hr>
			</p>
		<?php
			if(strlen($status) > 0) {
				$imgPath = saveImage();
				if(strlen($imgPath) > 0) {
					$imageUrl = getDirectoryUrl() . $imgPath;
					//echo "Image saved as : "  . $imageUrl;
					$status = $imageUrl . " " . $status;
					
				}
				requestToTwitter('http://twitter.com/statuses/update.xml?status=' . urlencode($status), $userName, $password);
			}
			if(requestToTwitter('http://twitter.com/statuses/friends_timeline.xml', $userName, $password) > 0) {
				showPrivateFeed($twitterResponse);			
			}
		}	//		
		
		
	function checkItem($itemName) {
		if(isset($_POST[$itemName])) {
	  		return true; 
		}
		else {
			return false;
		}
	}
	/*
	function printUserText($text) {
		$pattern = "/http:\/\/([a-zA-Z0-9])/";
		$url =preg_match($pattern, $text);
		if($url) {
			print '<a href="';
			print $url;
			print '">';
			print $text . '</a></p><hr>';
		}
		else {
			print $text . '</p><hr>';
		}
	}*/
	
	function getDirectoryUrl() {
		$fullPath = "http://" . $_SERVER['HTTP_HOST']. $_SERVER['PHP_SELF'];
		$pos = strrpos($fullPath, "/");
		return substr($fullPath, 0, $pos + 1);
	}
	
	function formatUserText($text) {
		//test...
		$pos = strpos($text, "http://");
		if($pos === false) {
			print $text . '</p><hr>'; //not found, just print text
		}
		else {
			if($pos > 0) {
				print substr($text, 0, $pos);
			}
						
			$pos2 = strpos($text, ' ', $pos + 1);
			if($pos2 === false) {
				$pos2 = strlen($text);
			}
			
			
			$url = substr($text, $pos, $pos2 - $pos);
			if(strrpos($url, '.png') > 0 || strrpos($url, '.jpg') > 0 || strrpos($url, '.jpeg') > 0 || strrpos($url, '.gif') > 0) {
				print '<img src="';
				print $url;
				print '"/>';
			}
			else if((strrpos($url, '.amr') > 0) || (strrpos($url, '.wav') > 0)) {
				print '<object name="sound_file" classid="clsid:5eb72431-8e47-45a2-a6ba-609af9f051b9" type="player" src="' . $url . '"></object>';
			}
			else {
				print '<a href="';
				print $url;
				print '">';
				print $url .'</a>';				
			}
			
			$pos 		= $pos2;
			$pos2 		= strlen($text);
			if($pos2 > $pos) {
				$restText 	= substr($text, $pos, $pos2-$pos);
				print $restText;
			}
			print '</p><hr>';
		}	
	}
	
	function showPrivateFeed($response) {
		//print '<p>Response : ' . $response . '</p>';
		
		$feed = simplexml_load_string($response);
		print '<h3>Showing the latest private posts</h3><hr>';
		//print '<a href="http://demo.ilabs.no/test/widgets/twitter.php">update</a><br>';
		$i = 0;
		foreach($feed->status as $status) {
			print '<p>';
			print '<img src="';
			print $status->user->profile_image_url;
			print '"/><b>';
			print $status->user->screen_name . ' : </b><br>';
			formatUserText($status->text);
			//print $status->text . '</p><hr>';
			$i++;
			if($i>5) {
				break;
			}
		}
	}

	//print_r($_POST);
	$imgPath = '';
	
	function saveImage() {
				
		if(isset($_POST["update"]) && $_POST["update"] == "Update") {
			unset($imagename);
			
			if(!isset($_FILES) && isset($HTTP_POST_FILES))
				$_FILES = $HTTP_POST_FILES;
	
			if(!isset($_FILES['image_file'])) {
				$error["image_file"] = "An image was not found.";
				//echo $error;
				return "";
			}
	
			$imagename = basename($_FILES['image_file']['name']);
			//echo "FileName : " . $imagename;
	
			if(empty($imagename)) {
				$error["imagename"] = "The name of the image was not found.";
				echo $error;
				return "";
			}
	
			if(empty($error)) {
				$newimage = "img/" . urlencode($imagename);
				//echo $newimage;
				$result = @move_uploaded_file($_FILES['image_file']['tmp_name'], $newimage);
				
				$imgPath = $newimage;  
				if(empty($result)) {
					$error["result"] = "There was an error moving the uploaded file.";
					echo $error;
				}
				else {
					return $imgPath;
				}
			}
		}
		return "";
	}
	
	
	//Request to Twitter with cURL lib
	function requestToTwitter ($url, $userName, $passWord)
	{
		if(empty($userName) || empty($passWord))
		{
			Error(1);
		} else 
		{
			if(function_exists('curl_init'))
			{	
				$ch = curl_init();	
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_USERPWD, "$userName:$passWord");
				curl_setopt($ch, CURLOPT_POST, true);

				global $twitterResponse;
				$twitterResponse = curl_exec($ch);
				//print '<p>twitterResponse : ' . $twitterResponse . '</p>';
				
				$Headers = curl_getinfo($ch);
				curl_close($ch);

				//print '<p>twitterResponse2 : ' . $twitterResponse . '</p>';
					
				if($Headers['http_code'] == 200) {
					return 1;
				}
				//else 400 ..means twitter rate limit  
				else
				{
					if($Headers['http_code'] == 401)
					{
						Error(4);
					} elseif($Headers['http_code'] == 404)
					{
						Error(5);
					}
				}//Check Response
			} else
			{
				Error(2);
			}//CURL Library installed	
			
		}		
   } //end Messages XML Parse

	//Function to be called if error occurs
	function Error($Error){
		//List of Errors
		$e[1] = 'Username and/or password not set';
		$e[2] = 'CURL library not installed';
		$e[3] = 'Post value too long/not set';
		$e[4] = 'Invalid username/password';
		$e[5] = 'Invalud URL for CURL request';
		$e[6] = 'Invalid ID value entered';
		$e[7] = 'You are not authorized to view this page';
		$e[8] = 'All variables for requested function not set';
		$e[9] = 'For and/or Message not set';
		//Display Error
		if(array_key_exists($Error, $e)){
			echo $e[$Error];
		} else{
			echo 'Invalid Error Code';
		}
	}//End Error()	
	  	
	?>	
	</body>
</html>